package com.lancoo.answer.ui.ques.quesBody;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.google.gson.Gson;
import com.lancoo.answer.R;
import com.lancoo.answer.component.InteractWebView;
import com.lancoo.answer.model.AnswerConstant;
import com.lancoo.answer.model.ConstantBean;
import com.lancoo.answer.model.TaskState;
import com.lancoo.answer.model.bean.Child;
import com.lancoo.answer.model.bean.Item;
import com.lancoo.answer.model.bean.ItemAsk;
import com.lancoo.answer.model.bean.Ques;
import com.lancoo.answer.model.bean.Type;
import com.lancoo.answer.ui.ques.SpliteLayoutFragment;
import com.rxjava.rxlife.RxLife;

import org.jetbrains.annotations.NotNull;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import io.reactivex.Observable;
import io.reactivex.Single;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by pengmi on 2021/12/16 9:30
 * Description:翻译大题题干加载fragment
 */
public class TranslationQuseBodyFragment extends Fragment {

    private static final String TAG = "TranslationQuseBodyFrag";
    private FrameLayout frameLayout;
    private InteractWebView interactWebView;
    private Ques ques;
    boolean isClick = true;

    public static Fragment loadQueseFragment(int kindIndex, int queseIndex, int defaultIndex) {
        TranslationQuseBodyFragment queseFragment = new TranslationQuseBodyFragment();
        Bundle mBundle = new Bundle();
        mBundle.putInt(AnswerConstant.KEY_TYPEINDEX, kindIndex);
        mBundle.putInt(AnswerConstant.KEY_QUESINDEX, queseIndex);
        mBundle.putInt(AnswerConstant.KEY_LOADCHILDINDEX, defaultIndex);
        queseFragment.setArguments(mBundle);
        return queseFragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.ev_fragment_ques_body, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (getArguments() == null || getContext() == null || getActivity() == null) {
            return;
        }
        List<Type> kindBeanListk = ConstantBean.Companion.getConstantExamBean().getTypeList();
        if (kindBeanListk == null) {
            return;
        }
        int typeIndex = getArguments().getInt(AnswerConstant.KEY_TYPEINDEX);
        int quesIndex = getArguments().getInt(AnswerConstant.KEY_QUESINDEX);
        if (kindBeanListk.get(typeIndex) == null ||
                kindBeanListk.get(typeIndex).getQuesList() == null) {
            return;
        }

        ques = kindBeanListk.get(typeIndex).getQuesList().get(quesIndex);
        interactWebView = new InteractWebView(getContext());
        interactWebView.setBackgroundColor(0xfff7f7f7);
        if (ques == null || ques.getQuesBody() == null) {
            return;
        }
        frameLayout = view.findViewById(R.id.framelayout);
        frameLayout.addView(interactWebView);
        Log.e(TAG, "onViewCreated loadWebView");
        String quesBody = ques.getQuesBody();//大题题干
//        StringBuilder builder = new StringBuilder();
        Boolean isIndentation = ques.getIsIndentQuesBody();
        if (TextUtils.isEmpty(quesBody)) {//为空，取小题题干
            if (ques.getChildList() != null && ques.getChildList().size() > 0) {
                quesBody = ques.getChildList().get(0).getChildAsk();
                isIndentation = ques.getChildList().get(0).getIsIndentChildAsk();
            }
        }
//        for (int i = 0; i < 1; i++) {
//            builder.append(quesBody);
//        }
        if (quesBody == null) {
            quesBody = "";
        } else {
            quesBody = "<style type=\"text/css\">.znbk-clauseindex{padding-right:3px;}</style>" + quesBody;
        }
        interactWebView.setQues(ques);
        interactWebView.setIsIndentation(isIndentation);
        interactWebView.initWebView(getActivity(), quesBody, new InteractWebView.Callback() {
            @Override
            public void clickCallback(@NotNull String position) {
                Log.e("eee", "触发了点击" + position);
                boolean enableClick = ConstantBean.getTaskState() == TaskState.TRAINING ||
                        TextUtils.equals(ques.getGenreID(), "50") ||
                        TextUtils.equals(ques.getGenreID(), "51");
                if (enableClick) {
                    if (isClick) {
                        wvLoadUrl(position);
                        getItemIndexToQuesBody(position);
                        isClick = false;

                    }
                    new Handler().postDelayed(() -> isClick = true, 300);
                }
            }

            @Override
            public void finishCallback() {
                initLayout();
                interactWebView.showOrHideClauseIndex(1);
                if (ConstantBean.getTaskState() != TaskState.TRAINING) {
                    switch (ques.getGenreID()) {
                        case "39":
                        case "41":
                            interactWebView.showOrHideClauseIndex(0);
                            return;
                    }
                }
                if (getArguments() != null) {
                    int loadChildIndex = getArguments().getInt(AnswerConstant.KEY_LOADCHILDINDEX);
                    if (loadChildIndex < 0) {
//                        onClickItemIndex(0, 0);
                    }
                }
                if (ConstantBean.getTaskState() == TaskState.TRAINING) {
                    Observable.timer(200, TimeUnit.MILLISECONDS)//必须加延时才能算准高度
                            .observeOn(AndroidSchedulers.mainThread())
                            .as(RxLife.as(TranslationQuseBodyFragment.this))
                            .subscribe(aLong -> {
                                if (getArguments() == null) {
                                    return;
                                }
                                openPalette();
                            });
                }
            }
        });
    }

    private void openPalette() {
        SharedPreferences sharedPreferences = getContext().getSharedPreferences(AnswerConstant.SP_ANSWER_NAME, Context.MODE_PRIVATE);
        boolean openDash = sharedPreferences.getBoolean(AnswerConstant.SP_OPEN_DASH, false);
        if (openDash) {
            interactWebView.openPalette();
        } else {
            interactWebView.closePalette();
        }
    }

    //答题点下划线，高亮等等绘制
    private void wvLoadUrl(String position) {
        interactWebView.scrollTranslatePosition(position);
        switch (ques.getGenreID()) {
            case "50": //句子定向英译中
            case "51": {
                for (Child child : ques.getChildList()) {
                    String itemSortIndex = child.getItemList().get(0).getItemSortIndex();
                    if (getPosition(position).equals(getPosition(itemSortIndex))) {
                        interactWebView.loadTranslateUrl(position, true);
                    } else {
                        String lineIndex = getPosition(itemSortIndex);
                        interactWebView.loadTranslateUrl("underline" + lineIndex, false);
                    }
                }
                return;
            }
            default: {
                List<Child> childList = ques.getChildList();
                if (childList == null || childList.size() == 0) {
                    return;
                }
                Child child = childList.get(0);
                List<Item> itemList = child.getItemList();
                if (itemList == null || itemList.size() == 0) {
                    return;
                }
                Item item = itemList.get(0);
                if (item == null) {
                    return;
                }
                List<ItemAsk> itemAskList = item.getItemAskList();
                if (itemAskList == null || itemAskList.size() == 0) {
                    return;
                }
                for (ItemAsk ask : itemAskList) {
                    String askTip = getPosition(ask.getAskTip());
                    String itemSortIndex = "underline" + ques.getChildList().get(0).getItemList().get(0).getItemSortIndex() + "-" + askTip;
                    if (itemSortIndex.equals(position)) {
                        interactWebView.loadTranslateUrl(position, true);
                    } else {
                        interactWebView.loadTranslateUrl(itemSortIndex, false);
                    }
                }
            }
        }
    }

    public String getPosition(String args) {
        String regEx = "[^0-9]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(args);
        return m.replaceAll("").trim();
    }

    public void onClickItemIndex(int childIndex, int itemIndex) {
        switch (ques.getGenreID()) {
            case "50":
            case "51": {
                String index = ques.getChildList().get(childIndex).getItemList().get(0).getItemSortIndex();
                wvLoadUrl("underline" + index);
                return;
            }
            default: {
                List<ItemAsk> itemAskList = ques.getChildList().get(0).getItemList().get(0).getItemAskList();
                if (itemAskList == null || itemAskList.size() == 0) {
                    return;
                }
                String askTip = ques.getChildList().get(0).getItemList().get(0).getItemAskList().get(itemIndex).getAskTip();
                String lineIndex = "underline" + ques.getChildList().get(0).getItemList().get(0).getItemSortIndex() + "-" + getPosition(askTip);
                interactWebView.setVerticalScrollbarPosition(1);
                wvLoadUrl(lineIndex);
            }
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        switch (ques.getGenreID()) {
            case "50": //句子定向英译中
            case "51": {
                for (Child child : ques.getChildList()) {
                    String itemSortIndex = child.getItemList().get(0).getItemSortIndex();
                    String lineIndex = getPosition(itemSortIndex);
                    interactWebView.loadTranslateUrl("underline" + lineIndex, false);
                }
                return;
            }
            default: {
                List<Child> childList = ques.getChildList();
                if (childList == null || childList.size() == 0) {
                    return;
                }
                Child child = childList.get(0);
                List<Item> itemList = child.getItemList();
                if (itemList == null || itemList.size() == 0) {
                    return;
                }
                Item item = itemList.get(0);
                if (item == null) {
                    return;
                }
                List<ItemAsk> itemAskList = item.getItemAskList();
                if (itemAskList == null || itemAskList.size() == 0) {
                    return;
                }
                for (ItemAsk ask : itemAskList) {
                    String askTip = getPosition(ask.getAskTip());
                    String itemSortIndex = "underline" + ques.getChildList().get(0).getItemList().get(0).getItemSortIndex() + "-" + askTip;
                    interactWebView.loadTranslateUrl(itemSortIndex, false);
                }
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (interactWebView != null) {
            interactWebView.release();
        }
        if (frameLayout != null) {
            frameLayout.removeAllViews();
        }
    }

    private void getItemIndexToQuesBody(String itemIndexStr) {
        if (ques.getChildList() == null) {
            return;
        }
        List<Child> childList = ques.getChildList();
        if (childList.size() == 1) {
            List<Item> itemList = childList.get(0).getItemList();
            if (itemList == null) {
                return;
            }
            if (itemList.size() == 1) {
                Item item = itemList.get(0);
                List<ItemAsk> itemAskList = item.getItemAskList();
                if (itemAskList == null) {
                    return;
                }
                for (int i = 0; i < itemAskList.size(); i++) {
                    ItemAsk itemAsk = itemAskList.get(i);
                    if (getPosition(itemIndexStr).equals(getPosition(itemList.get(0).getItemSortIndex() + itemAsk.getAskTip()))) {
                        Log.e(TAG, "遍历后的下标：" + i);
                        jumpToAimItemQues(-1, i);
                        return;
                    }
                }
            } else {
                for (int i = 0; i < itemList.size(); i++) {
                    Item item = itemList.get(i);
                    List<ItemAsk> itemAskList = item.getItemAskList();
                    if (itemAskList == null) {
                        return;
                    }
                    ItemAsk itemAsk = itemAskList.get(0);
                    if (getPosition(itemIndexStr)
                            .equals(getPosition(itemList.get(i).getItemSortIndex() + itemAsk.getAskTip()))) {
                        Log.e(TAG, "遍历后的下标：" + i);
                        jumpToAimItemQues(-1, i);
                        return;
                    }
                }
            }
        } else {

            for (int i = 0; i < childList.size(); i++) {
                Child child = childList.get(i);
                Log.e(TAG, new Gson().toJson(child));
                List<Item> itemList = child.getItemList();
                if (itemList == null) {
                    return;
                }
                Item item = itemList.get(0);

                String itemSortIndex = item.getItemSortIndex();
                if (getPosition(itemIndexStr)
                        .equals(getPosition(itemSortIndex))) {
                    Log.e(TAG, "定向翻译 遍历后的下标：" + i);
                    jumpToAimItemQues(i, -1);
                    return;
                }
            }
        }
    }

    private void jumpToAimItemQues(int childIndex, int itemIndex) {
        Single.timer(0, TimeUnit.MILLISECONDS).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .as(RxLife.as(this))
                .subscribe(aLong -> {
                    if (getParentFragment() instanceof SpliteLayoutFragment) {
                        SpliteLayoutFragment spliteLayoutFragment = ((SpliteLayoutFragment) getParentFragment());
                        if (childIndex >= 0) {
                            Log.e("pm", "jumpToAimItemQues:" + childIndex + "..." + itemIndex);
                            spliteLayoutFragment.jumpToAimChildFragment(childIndex, 0, 2);
                        }
                        if (itemIndex >= 0) {
                            Log.e("pm", "jumpToAimItemQues:" + childIndex + "..." + itemIndex);
                            spliteLayoutFragment.jumpToAimItemFragment(itemIndex);
                        }
                    }
                });
    }

    public void adjustFontSize(){
        if(interactWebView!=null){
            interactWebView.setFontSize();
        }
    }

    public void initLayout() {
        Fragment parentFragment = getParentFragment();
        if (parentFragment instanceof SpliteLayoutFragment) {
            ((SpliteLayoutFragment) parentFragment).initLayout();
        }
    }
}